/**
 * 带翻页功能的表格List
 * @author HuangS
 */
Ext.define('PJ.view.trainingmanagement.DefaultList', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.trainingmanagementDefaultgrid',
    multiSelect: true,
    selModel: {
        selType: 'checkboxmodel',
        // 设置为只能通过复选框选中行
        checkOnly: true
    },
    viewConfig: {
        loadMask: true,
        loadingText: default_lang.defaultList_loadingText,
        // 允许可选择表格内容进行复制
        enableTextSelection: true
    },
    /**
     * 翻页工具条是否可以生效，默认为true，即翻页工具条失效,如果左侧为tree型,建议将此属性默认修改为false
     */
    isPossibleLoad: true,
    /**
     * 是否显示翻页工具条,默认显示,false为不显示
     */
    isHavePage: true,
    /**
     * 是否自动加载绑定的store的数据,默认为true,false为不自动加载
     */
    isAutoLoad: true,
    initComponent: function(){
        if (this.isAutoLoad) {
            this.addListener("afterrender", function(){
            	debugger;
                this.store.load({
                    scope: this,
                    callback: function(records, operation, success) {
                        // 对象 operation 包含
                        // 所有 load 操作的详细信息
                        console.log(records);
                    }
                });
            });
        }
        // 创建权限过滤事件，需要每个列表在最后加载完成后手工触发
        this.addEvents('permission');
        if (this.isHavePage) {
            this.addListener("viewready", function(){
                this.addDocked([{
                    xtype: 'pagingtoolbar',
                    store: this.store,
                    dock: 'bottom',
                    displayInfo: true,
                    items: ['-', {
                        xtype: "combo",
                        queryMode: 'local',
                        store: new Ext.data.ArrayStore({
                            fields: ['value', 'text'],
                            data: [[10, default_lang.defaultList.pagination[0]], [20, default_lang.defaultList.pagination[1]], [50, default_lang.defaultList.pagination[2]], [100, default_lang.defaultList.pagination[3]], [200, default_lang.defaultList.pagination[4]], [500, default_lang.defaultList.pagination[5]]]
                        }),
                        valueField: 'value',
                        displayField: 'text',
                        width: 80,
                        editable: false,
                        listeners: {
                            afterrender: function(combo){
                            	debugger;
                                combo.setValue(10);
                                var gridPanel = combo.up("grid");
                                gridPanel.resetPage();
                                var gridStore = gridPanel.getStore();
                                gridStore.pageSize = combo.getValue();
                            },
                            select: function(combo){
                            	debugger;
                                var gridPanel = combo.up("grid");
                                if (gridPanel.isPossibleLoad) {
                                    gridPanel.resetPage();
                                    var gridStore = gridPanel.getStore();
                                    gridStore.pageSize = combo.getValue();
                                    gridStore.load();
                                }
                                else {
                                    combo.setValue(10);
                                }
                            }
                        }
                    }],
                    listeners: {
                        beforechange: function(pageBar, page){
                            return pageBar.up("grid").isPossibleLoad;
                        }
                    }
                }]);
            });
        }
        // 创建grid时清除以前的缓存数据
        this.resetPage();
        this.addListener("selectionchange", function(selModel, selected){
            if (this.down('#' + this.oldId + "Update")) {
                this.down('#' + this.oldId + "Update").setDisabled(selected.length === 0);
            }
            if (this.down('#' + this.oldId + "Delete")) {
                this.down('#' + this.oldId + "Delete").setDisabled(selected.length === 0);
            }
            if (this.down('#' + this.oldId + "Reuse")) {
                this.down('#' + this.oldId + "Reuse").setDisabled(selected.length === 0);
            }
            if (this.down('#' + this.oldId + "Discard")) {
                this.down('#' + this.oldId + "Discard").setDisabled(selected.length === 0);
            }
            if (this.down("#totalCount")) {
                this.down("#totalCount").setText(default_lang.defaultList.totalCount[0] + '：<span style="color: red;">' + selected.length + default_lang.defaultList.totalCount[1] + '</span>', false);
            }
        });
        var clazzName = this.$className;
        var tempUrl = clazzName.split(".")[2] + "." + clazzName.split(".")[3];
        this.url = tempUrl;
        // 加入功能权限过滤
        this.addListener("permission", function(com){
            // 获取权限
            var cp = Ext.create('Ext.state.CookieProvider');
            Ext.state.Manager.setProvider(cp);
            var Obj = cp.get("permissions");
            if (!Obj) {
                return;
            }
            // 解析当前表格，获取权限集合
            var permissions = Obj[this.$className];
            if (permissions) {
                var me = this;
                Ext.each(permissions, function(value){
                    var num = Ext.Number.from(value, -1);
                    if (num == -1) {
                        // 非数字,上方button
                        var DelButton = me.down("#" + me.oldId + value);
                        if (DelButton) {
                            DelButton.hide();
                            var next = DelButton.next();
                            if (next) {
                                next.hide();
                            }
                        }
                    }
                    else {
                        // 数字,actioncolumn
                        var action = me.down("actioncolumn");
                        if (action) {
                            action.items.splice(num, 1, {
                                iconCls: "action-hidden"
                            });
                        }
                    }
                });
                
            }
        });
        this.getSelectionModel().bindStore(this.store);
        this.callParent(arguments);
    },
    /**
     * 重置翻页属性方法
     */
    resetPage: function(){
        this.store.currentPage = 1;
        // 刷新排序
        this.store.sorters.clear();
        //this.store.removeAll(true);
        // this.getSelectionModel().deselectAll(true);
    },
    /**
     * 清除表格中全部数据方法
     */
    removeAllRecords: function(){
        var store = this.store;
        var length = store.getCount();
        for (var i = length - 1; i >= 0; i--) {
            store.removeAt(i);
        }
    },
    /**
     * 新增按钮
     */
    addButton: {
        text: orchid_lang.buttons.addButtonText,
        iconCls: 'addIco',
        itemId: this.oldId + "Add",
        scope: this,
        handler: function(button){
            button.up("grid").onAddClick(button);
        }
    },
    onAddClick: null,
    updateButton: {
        text: orchid_lang.buttons.updateButtonText,
        iconCls: 'editIco',
        itemId: this.oldId + "Update",
        disabled: true,
        handler: function(button){
            if (button.up("grid").getSelectionModel().getCount() > 1) {
                Ext.Msg.show({
                    title: orchid_lang.promptWindowInfo.warningTitle,
                    msg: default_lang.defaultList.operatingWarningMsg,
                    icon: Ext.Msg.WARNING,
                    buttons: Ext.Msg.OK
                });
                return;
            }
            else {
                button.up("grid").onUpdateClick(button);
            }
        }
    },
    onUpdateClick: null,
    /**
     * 启用按钮
     */
    reuseButton: {
        text: orchid_lang.buttons.reuseButtonText,
        disabled: true,
        itemId: this.oldId + "Reuse",
        iconCls: 'reuseIco',
        handler: function(button){
            button.up("grid").onReuseClick(button);
        }
    },
    onReuseClick: null,
    /**
     * 作废按钮
     */
    discardButton: {
        text: orchid_lang.buttons.discardButtonText,
        disabled: true,
        itemId: this.oldId + "Discard",
        iconCls: 'discardIco',
        handler: function(button){
            button.up("grid").onDiscardClick(button);
        }
    },
    onDiscardClick: null,
    /**
     * 删除按钮
     */
    deleteButton: {
        text: orchid_lang.buttons.deleteButtonText,
        disabled: true,
        itemId: this.oldId + "Delete",
        iconCls: 'deleteIco',
        handler: function(button){
            button.up("grid").onDeleteClick(button);
        }
    },
    /**
     * 删除按钮点击事件
     */
    onDeleteClick: null,
    
    // 搜索条件相关
    projectNameText: function(url){
        var me = this;
        if (url != null && url != "") {
            me.url = url;
        }
        var combo = Ext.create('Ext.form.field.ComboBox', {
            labelAlign: 'right',
            labelWidth: 70,
            allowBlank: false,
            blankText: default_lang.defaultList.searchProjectId_blankText,
            itemId: "projectNameText",
            name: 'searchProjectId',
            fieldLabel: default_lang.defaultList.searchProjectId,
            emptyText: orchid_lang.pageVerificationInfo.combo_emptyText,
            queryMode: 'remote',
            store: Ext.create('Ext.data.Store', {
                fields: [{
                    name: 'value',
                    mapping: "projectId",
                    type: 'string'
                }, {
                    name: 'text',
                    mapping: "projectName",
                    type: 'string'
                }],
                proxy: {
                    type: 'ajax',
                    url: "module/projectconfigure/prostaleaderrelation/findProjectList.json?functionCode=" + me.url,
                    reader: Ext.create('Ext.data.reader.Json', {
                        type: 'json',
                        root: 'data',
                        successProperty: 'success'
                    })
                }
            }),
            
            valueField: 'value',
            displayField: 'text',
            editable: false,
            
            listeners: {
                change: function(combo, newValue){
                    if (newValue == null || newValue == "") {
                        return;
                    }
                    var deptNameText = combo.up("form").down("#deptNameText");
                    if (deptNameText) {
                        var store = deptNameText.getStore();
                        var newParams = {
                            searchProjectId: combo.getValue(),
                            functionCode: me.url
                        };
                        var params = store.proxy.extraParams;
                        Ext.apply(params, newParams);
                        deptNameText.clearValue();
                        store.load();
                    }
                    else {
                        var stationNameText = combo.up("form").down("#stationNameText");
                        if (stationNameText) {
                            var store = stationNameText.getStore();
                            var newParams = {
                                searchProjectId: combo.getValue(),
                                functionCode: me.url
                            };
                            var params = store.proxy.extraParams;
                            Ext.apply(params, newParams);
                            stationNameText.clearValue();
                            store.load();
                        }
                    }
                }
            }
        });
        return combo;
    },
    deptNameText: function(){
        var me = this;
        var combo = Ext.create('Ext.form.field.ComboBox', {
            labelAlign: 'right',
            labelWidth: 70,
            itemId: "deptNameText",
            name: 'searchCompanyId',
            fieldLabel: default_lang.defaultList.searchCompanyId,
            emptyText: orchid_lang.pageVerificationInfo.combo_emptyText,
            queryMode: 'local',
            store: Ext.create('Ext.data.Store', {
                fields: [{
                    name: 'value',
                    mapping: "deptId",
                    type: 'string'
                }, {
                    name: 'text',
                    mapping: "deptName",
                    type: 'string'
                }],
                proxy: {
                    type: 'ajax',
                    url: "module/projectconfigure/prostaleaderrelation/findDepartmentList.json",
                    reader: Ext.create('Ext.data.reader.Json', {
                        type: 'json',
                        root: 'data',
                        successProperty: 'success'
                    })
                }
            }),
            
            valueField: 'value',
            displayField: 'text',
            editable: false,
            listeners: {
                beforerender: function(combo){
                    var projectNameText = combo.up("form").down("#projectNameText");
                    if (!projectNameText) {
                        combo.getStore().load();
                    }
                },
                select: function(combo){
                    var stationNameText = combo.up("form").down("#stationNameText");
                    if (stationNameText) {
                    
                        var projectNameText = combo.up("form").down("#projectNameText");
                        var searchProjectId = "";
                        if (projectNameText) {
                            searchProjectId = projectNameText.getValue();
                        }
                        
                        var store = stationNameText.getStore();
                        var newParams = {
                            searchProjectId: searchProjectId,
                            searchDepID: combo.getValue(),
                            functionCode: me.url
                        };
                        var params = store.proxy.extraParams;
                        Ext.apply(params, newParams);
                        store.load();
                    }
                }
            }
        });
        return combo;
    },
    stationNameText: function(){
        var combo = Ext.create('Ext.form.field.ComboBox', {
            labelAlign: 'right',
            labelWidth: 70,
            itemId: "stationNameText",
            name: 'searchStationId',
            fieldLabel: default_lang.defaultList.searchStationId,
            emptyText: orchid_lang.pageVerificationInfo.combo_emptyText,
            queryMode: 'local',
            store: Ext.create('Ext.data.Store', {
                fields: [{
                    name: 'value',
                    mapping: "stationId",
                    type: 'string'
                }, {
                    name: 'text',
                    mapping: "stationName",
                    type: 'string'
                }],
                proxy: {
                    type: 'ajax',
                    actionMethods: {
                        read: 'POST'
                    },
                    url: "module/projectconfigure/prostaleaderrelation/findStationList.json",
                    reader: Ext.create('Ext.data.reader.Json', {
                        type: 'json',
                        root: 'data',
                        successProperty: 'success'
                    })
                },
                listeners: {
                    load: function(store, records, successful){
                        if (successful) {
                            Ext.each(records, function(record){
                                var value = record.get("value");
                                var text = record.get("text");
                                record.set({
                                    text: "【" + value + "】" + text
                                })
                            });
                        }
                    }
                }
            }),
            
            valueField: 'value',
            displayField: 'text',
            editable: false,
            listeners: {
                beforerender: function(combo){
                    var projectNameText = combo.up("form").down("#projectNameText");
                    var deptNameText = combo.up("form").down("#deptNameText");
                    if (!deptNameText && !projectNameText) {
                        combo.getStore().load();
                    }
                }
            }
        });
        return combo;
    },
    highSelectLabel: {
        xtype: 'label',
        padding: '0 15 0 0',
        text: '',
        itemId: 'highSelectLabel'
    },
    /**
     * 默认重置按钮点击事件
     * @param {Object} btn
     */
    defaultResetClick: function(btn){
        var form = btn.up('form');
        if (form.grid) {
            form.grid.getStore().proxy.extraParams = {};
            form.grid.highSearchData = null;
            var highSelectLabel = form.down("#highSelectLabel");
            if (highSelectLabel) {
                highSelectLabel.setText("");
            }
        }
        var projectValue;
        if (form.down("#projectNameText")) {
            projectValue = form.down("#projectNameText").getValue();
        }
        form.getForm().reset();
        // 有公司和岗位，在重置时删除全部数据
        if (form.down("#deptNameText")) {
            var store = form.down("#deptNameText").getStore();
            for (var i = store.getCount() - 1; i >= 0; i--) {
                store.removeAt(i);
            }
        }
        if (form.down("#stationNameText")) {
            var store = form.down("#stationNameText").getStore();
            for (var i = store.getCount() - 1; i >= 0; i--) {
                store.removeAt(i);
            }
        }
        var fields = form.getForm().getFields();
        fields.each(function(item, index, len){
            if (item.defaultValue || item.defaultValue == 0) {
                item.select(item.defaultValue);
            }
        });
        if (form.down("#projectNameText")) {
            form.down("#projectNameText").setValue(projectValue);
        }
        
    },
    /**
     * 重置按钮
     */
    resetButton: {
        xtype: "button",
        text: orchid_lang.buttons.resetButtonText,
        width: 90,
        itemId: "resetButton",
        listeners: {
            click: function(){
                var form = this.up('form');
                if (!form.onResetClick) {
                    form.grid.defaultResetClick(this);
                }
                else {
                    form.onResetClick(this);
                }
            }
        }
    },
    /**
     * 筛选按钮
     */
    selectButton: {
        xtype: "button",
        text: orchid_lang.buttons.selectButtonText+"111",
        width: 90,
        itemId: "selectButton",
        listeners: {
            click: function(){
                var form = this.up('form');
                debugger;
                if (!form.onSelectClick) {
                    if (form.grid) {
                    
                        var projectNameText = form.down("#projectNameText");
                        if (!form.getForm().isValid()) {
                            return;
                        }
                        
                        var newParams = form.getValues();
                        
                        var store = form.grid.getStore();
                        // 重置翻页属性
                        form.grid.resetPage();
                        
                        // 4.0强制更改store参数写法
                        var params = store.proxy.extraParams;
                        Ext.apply(params, newParams);
                        debugger;
                        store.load();
                    }
                    else {
                        Ext.Msg.show({
                            title: orchid_lang.promptWindowInfo.warningTitle,
                            msg: default_lang.defaultList.selectWarningMsg,
                            icon: Ext.Msg.WARNING,
                            buttons: Ext.Msg.OK
                        });
                    }
                }
                else {
                    form.onSelectClick(this);
                }
            }
        }
    },
    /**
     * 高级筛选按钮
     */
    highSelectButton: {
        text: orchid_lang.buttons.highSelectButtonText,
        itemId: "highSelectButton",
        listeners: {
            click: function(){
                var form = this.up('form');

                debugger;
                var projectNameText = form.down("#projectNameText");
                if (!form.getForm().isValid()) {
                    return;
                }
                
                Ext.create("AM.default.DefaultHighSearchFormWindow", {
                    grid: this.up("grid"),
                    form: form
                });
                //this.up('form').onHighSelectClick(this);
            }
        }
    },
    /**
     * 获取筛选和重置按钮组合的panel
     */
    searchButtonPanel: function(){
        var me = this;
        var panel = Ext.create("Ext.container.Container", {
            layout: {
                type: 'hbox',
                padding: '5',
                pack: 'end',
                align: 'middle'
            },
            items: [{
                xtype: 'tbfill'
            }, me.selectButton, {
                xtype: 'tbspacer'
            }, {
                xtype: 'tbspacer'
            }, {
                xtype: 'tbspacer'
            }, me.resetButton]
        });
        return panel;
    },
    /**
     * 已选择记录数panel
     */
    countSelectPanel: {
        xtype: 'label',
        itemId: 'totalCount',
        html: default_lang.defaultList.totalCount[0] + '：<span style="color: red;">0' + default_lang.defaultList.totalCount[1] + '</span>'
    }
});
